import 'package:cached_network_image/cached_network_image.dart';
import "package:flutter/material.dart";
import 'package:flutter_svg/flutter_svg.dart';
import 'package:intl/intl.dart';

String fromNow(datetime) {
    final _now = new DateTime.now();
    final _datetime = datetime is String ? DateTime.parse(datetime) : DateTime
        .fromMillisecondsSinceEpoch(datetime * 1000);
    final _diff = _now.difference(_datetime);
    if (_diff.inMinutes < 60) {
        return '${_diff.inMinutes}分钟之前';
    } else if (_diff.inHours < 10) {
        return '${_diff.inHours} 小时以前';
    } else {
        return '${_datetime.year}年${_datetime.month}月${_datetime
            .day}日 ${_datetime.hour}:${_datetime.minute}:${_datetime.second}';
    }
}

SizedBox getSizedIcon({double height = 30.0, double width = 30.0, @required String path, @required String icon}) {
    return new SizedBox(
        width: width,
        height: height,
        child: getIcon(path, icon),
    );
}

SvgPicture getIcon(String path, String icon) {
    return new SvgPicture.asset("assets/images/$path/$icon.svg");
}

ClipOval getNetworkImage({double height = 48.0, double width = 48.0, @required String iconSrc}) {
    return ClipOval( // 可以使用 CircleAvatar
        child: CachedNetworkImage(
            width: height,
            height: width,
            fit: BoxFit.fitHeight,
            placeholder:(context, url) => CircularProgressIndicator(),
            imageUrl: iconSrc,
        ),
    );
}

String formatUrl(String url) {
    return url.startsWith('//') ? 'https:$url' : url;
}

List<Widget> toWidgetList(list) {
    var children = <Widget>[];
    list.forEach((item) {
        children.add(item);
    });
    return children;
}

String dateFormat(date, pattern, [bool pureNumber]) {
    if (date is String) {
        date = DateTime.parse(date);
    }
    if (pureNumber == null) {
        pureNumber = false;
    }
    return (pureNumber ? DateFormat(pattern) : DateFormat(pattern, 'ja')).format(date.toLocal());
}

ktToast(context, errorMsg, {milliseconds = 800}) {
    return Scaffold.of(context).showSnackBar(new SnackBar(
        content: new Text('$errorMsg'),
        duration: Duration(milliseconds: milliseconds),
    ));
}

